import pymysql

# MySQL连接配置
host = 'localhost'
user = 'root'
password = 'root'
database = 'dict'

# 连接到MySQL数据库
conn = pymysql.connect(host=host, user=user, password=password, database=database)
cursor = conn.cursor()

# 准备dict.txt文件的路径和解析函数
dict_file = '../baidu/dict.txt'

def parse_line(line):
    parts = line.split('  ', 1)
    word = parts[0].strip()
    definition = parts[1].strip() if len(parts) > 1 else ''
    return word, definition

# 读取文件并插入数据
with open(dict_file, 'r', encoding='utf-8') as file:
    for line in file:
        if line.strip():
            try:
                word, definition = parse_line(line)
                insert_query = "INSERT INTO words (word, definition) VALUES (%s, %s)"
                cursor.execute(insert_query, (word, definition))
            except Exception as e:
                print(f"Error processing line: {line}")
                print(e)

# 提交事务
conn.commit()

# 关闭连接
cursor.close()
conn.close()
